import ctypes
import os
import subprocess

from PyQt6.QtCore import Qt, QUrl
from PyQt6.QtGui import QDesktopServices, QIcon
from PyQt6.QtWidgets import QWidget, QVBoxLayout, QPushButton, QLabel


class InitWindow(QWidget):
    """
    初始化运行环境
    设置adb到环境变量中
    """

    def __init__(self):
        super().__init__()
        # set application icon
        myappid = 'mycompany.myproduct.subproduct.version'
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)

        current_dir = os.getcwd()
        self.platform_tools_dir = os.path.join(current_dir, "platform-tools")

        self.setWindowTitle("Phone Tools")
        self.setMaximumSize(300, 400)
        self.setFixedSize(300, 400)
        self._center_window()
        self.icon_path = os.path.join(self.platform_tools_dir, 'icon.ico')
        self.setWindowIcon(QIcon(self.icon_path))

        # 创建按钮
        self.set_adb_button = QPushButton("配置环境", self)
        self.set_adb_button.setGeometry(100, 150, 100, 30)  # 设置按钮位置
        self.set_adb_button.clicked.connect(self.set_adb)

        # 创建标签
        self.label = QLabel('配置环境后重启软件', self)
        self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)

        # 创建布局
        layout = QVBoxLayout()
        # layout.addWidget(self.set_adb_button)
        layout.addStretch(0)  # 添加可伸缩的空间
        layout.addWidget(self.label)

        self.setLayout(layout)

    def _center_window(self):
        # 获取当前屏幕的几何信息
        screen = self.screen().availableGeometry()
        # 获取窗口的几何信息
        size = self.geometry()
        # 计算窗口应该移动到的位置，使其居中
        x = (screen.width() - size.width()) // 2
        y = (screen.height() - size.height()) // 2
        # 移动窗口到计算的位置
        self.move(x, y)

    def set_adb(self):
        # 配置adb到系统环境变量中
        if self._check_evn() == False: return
        "将adb目录加入系统环境变量"
        try:
            command = f'setx Path "%PATH%;{self.platform_tools_dir}" /M'
            ctypes.windll.shell32.ShellExecuteW(None, "runas", "cmd.exe", f"/k {command}", None, 1)
            # 关闭窗口
        except Exception as e:
            self.label.setText(e)
        else:
            self.label.setText("配置环境完成,重启软件")
            self.window().close()

    def _check_evn(self):
        """
        在adb目录下执行adb，确认目录是否完整
        @return:
        """
        try:
            subprocess.run(["adb", "version"], shell=True, cwd=self.platform_tools_dir, check=True)
        except Exception as e:
            self.label.setText(f"环境损坏,重新下载")
            self._open_url()
            return False
        else:
            return True

    def _open_url(self):
        # 使用说明
        url = QUrl("https://docs.qq.com/doc/p/fbc6c34b104654ac414b00f6f3e15504a5009cda")
        QDesktopServices.openUrl(url)
